<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教师管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .btn-add {
            background-color: #27ae60;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-add:hover {
            background-color: #219653;
        }

        .search-box {
            margin-bottom: 20px;
        }

        .search-box input {
            width: 300px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-box button {
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        table th,
        table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        table th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        table tr:hover {
            background-color: #f5f5f5;
        }

        .action-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 13px;
        }

        .action-btn.edit {
            background-color: #f39c12;
        }

        .action-btn.delete {
            background-color: #e74c3c;
        }

        .action-btn:hover {
            opacity: 0.9;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 8px;
            padding: 30px;
            width: 500px;
            max-width: 90%;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-title {
            margin: 0;
            font-size: 20px;
            color: #333;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #777;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            text-align: right;
            margin-top: 20px;
        }

        .form-actions button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-cancel {
            background-color: #eee;
            color: #333;
            border: 1px solid #ddd;
            margin-right: 10px;
        }

        .btn-submit {
            background-color: #3498db;
            color: white;
            border: none;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li class="active"><a href="/admin/teachers">教师管理</a></li>
                <li><a href="/admin/students">学生管理</a></li>
                <li><a href="/admin/courses">课程管理</a></li>
                <li><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li><a href="/admin/course-selections">选课管理</a></li>
                <li><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>教师管理</h1>
                <button class="btn-add" onclick="openAddModal()">添加教师</button>
            </div>

            <div class="search-box">
                <input type="text" id="searchInput" placeholder="请输入教师姓名或工号">
                <button onclick="searchTeachers()">搜索</button>
            </div>

            <table id="teachersTable">
                <thead>
                    <tr>
                        <th>工号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>院系</th>
                        <th>职称</th>
                        <th>入职日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="teachersList">
                    <!-- 教师数据将通过AJAX动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加教师模态框 -->
    <div class="modal" id="addModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加教师</h3>
                <button class="close-btn" onclick="closeAddModal()">&times;</button>
            </div>
            <form id="addTeacherForm">
                <div class="form-group">
                    <label for="teacherId">教师工号</label>
                    <input type="text" id="teacherId" name="teacherId" required>
                </div>
                <div class="form-group">
                    <label for="name">姓名</label>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="gender">性别</label>
                    <select id="gender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="department">院系</label>
                    <input type="text" id="department" name="department" required>
                </div>
                <div class="form-group">
                    <label for="title">职称</label>
                    <select id="title" name="title" required>
                        <option value="教授">教授</option>
                        <option value="副教授">副教授</option>
                        <option value="助教">助教</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="birthDate">出生日期</label>
                    <input type="date" id="birthDate" name="birthDate" required>
                </div>
                <div class="form-group">
                    <label for="hireDate">入职日期</label>
                    <input type="date" id="hireDate" name="hireDate" required>
                </div>
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeAddModal()">取消</button>
                    <button type="button" class="btn-submit" onclick="addTeacher()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑教师模态框 -->
    <div class="modal" id="editModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑教师</h3>
                <button class="close-btn" onclick="closeEditModal()">&times;</button>
            </div>
            <form id="editTeacherForm">
                <input type="hidden" id="editTeacherId" name="teacherId">
                <input type="hidden" id="editUserId" name="userId">
                <div class="form-group">
                    <label for="editName">姓名</label>
                    <input type="text" id="editName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="editGender">性别</label>
                    <select id="editGender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editDepartment">院系</label>
                    <input type="text" id="editDepartment" name="department" required>
                </div>
                <div class="form-group">
                    <label for="editTitle">职称</label>
                    <select id="editTitle" name="title" required>
                        <option value="教授">教授</option>
                        <option value="副教授">副教授</option>
                        <option value="助教">助教</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editBirthDate">出生日期</label>
                    <input type="date" id="editBirthDate" name="birthDate" required>
                </div>
                <div class="form-group">
                    <label for="editHireDate">入职日期</label>
                    <input type="date" id="editHireDate" name="hireDate" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                    <button type="button" class="btn-submit" onclick="updateTeacher()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 页面加载完成后获取教师列表
        document.addEventListener('DOMContentLoaded', function () {
            // 检查当前用户信息
            console.log('Current user in session:', document.querySelector('.user-info').textContent.trim());
            fetchTeachers();
        });

        // 获取教师列表
        function fetchTeachers() {
            fetch('/api/admin/teachers', {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取教师列表失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    renderTeachers(data);
                })
                .catch(error => {
                    console.error('获取教师列表失败:', error);
                    alert('获取教师列表失败: ' + error.message);
                });
        }

        // 渲染教师列表
        function renderTeachers(teachers) {
            console.log("开始渲染教师列表...");
            const tableBody = document.getElementById('teachersList');
            tableBody.innerHTML = '';

            if (teachers.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="7" style="text-align: center;">暂无教师数据</td>';
                tableBody.appendChild(row);
                console.log("教师列表为空");
                return;
            }

            teachers.forEach(teacher => {
                // 安全转义教师ID，防止特殊字符导致问题
                const safeId = teacher.teacherId.replace(/'/g, "\\'").replace(/"/g, '\\"');
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${teacher.teacherId}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.gender}</td>
                    <td>${teacher.department}</td>
                    <td>${teacher.title}</td>
                    <td>${formatDate(teacher.hireDate)}</td>
                    <td>
                        <button class="action-btn edit" data-id="${safeId}">编辑</button>
                        <button class="action-btn delete" data-id="${safeId}">删除</button>
                    </td>
                `;
                
                // 添加点击事件监听器
                const editButton = row.querySelector('.edit');
                const deleteButton = row.querySelector('.delete');
                
                editButton.addEventListener('click', function() {
                    console.log("编辑按钮被点击，教师ID:", safeId);
                    openEditModal(safeId);
                });
                
                deleteButton.addEventListener('click', function() {
                    console.log("删除按钮被点击，教师ID:", safeId);
                    deleteTeacher(safeId);
                });
                
                tableBody.appendChild(row);
            });
            console.log(`成功渲染 ${teachers.length} 个教师`);
        }

        // 格式化日期
        function formatDate(dateString) {
            console.log('Formatting date:', dateString);
            if (!dateString) {
                console.log('Date string is empty or null');
                return '';
            }
            try {
                const date = new Date(dateString);
                if (isNaN(date.getTime())) {
                    console.log('Invalid date:', dateString);
                    return '';
                }
                const formattedDate = date.toISOString().split('T')[0];
                console.log('Formatted date:', formattedDate);
                return formattedDate;
            } catch (error) {
                console.error('Error formatting date:', error);
                return '';
            }
        }

        // 搜索教师
        function searchTeachers() {
            const searchTerm = document.getElementById('searchInput').value.trim();

            if (searchTerm === '') {
                fetchTeachers();
                return;
            }

            fetch(`/api/admin/teachers/search?term=${encodeURIComponent(searchTerm)}`)
                .then(response => response.json())
                .then(data => {
                    renderTeachers(data);
                })
                .catch(error => {
                    console.error('搜索教师失败:', error);
                });
        }

        // 打开添加教师模态框
        function openAddModal() {
            document.getElementById('addTeacherForm').reset();
            document.getElementById('addModal').style.display = 'flex';
        }

        // 关闭添加教师模态框
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // 添加教师
        function addTeacher() {
            const teacherId = document.getElementById('teacherId').value.trim();
            const name = document.getElementById('name').value.trim();
            const gender = document.getElementById('gender').value;
            const department = document.getElementById('department').value.trim();
            const title = document.getElementById('title').value;
            const birthDate = document.getElementById('birthDate').value;
            const hireDate = document.getElementById('hireDate').value;
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!teacherId || !name || !department || !birthDate || !hireDate || !username || !password) {
                alert('请填写所有必填字段');
                return;
            }

            const teacherData = {
                teacherId,
                name,
                gender,
                department,
                title,
                birthDate,
                hireDate,
                username,
                password
            };

            fetch('/api/admin/teachers', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(teacherData)
            })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(text || '添加教师失败');
                        });
                    }
                    return response.json();
                })
                .then(() => {
                    closeAddModal();
                    fetchTeachers();
                })
                .catch(error => {
                    console.error('添加教师失败:', error);
                    alert('添加教师失败: ' + error.message);
                });
        }

        // 打开编辑教师模态框
        function openEditModal(teacherId) {
            console.log('Opening edit modal for teacher ID:', teacherId);
            
            if (!teacherId) {
                console.error("教师ID为空，无法打开编辑模态框");
                alert("错误：无法获取教师信息");
                return;
            }
            
            // 显示模态框并设置加载状态
            document.getElementById('editModal').style.display = 'flex';
            document.getElementById('editTeacherForm').innerHTML = '<div style="text-align: center; padding: 20px;">加载中...</div>';
            
            fetch(`/api/admin/teachers/${encodeURIComponent(teacherId)}`, {
                method: 'GET',
                credentials: 'include', // 包含凭证（Cookie）
                headers: {
                    'Accept': 'application/json'
                }
            })
                .then(response => {
                    console.log('Response status:', response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('教师不存在');
                            throw new Error('教师不存在');
                        }
                        return response.text().then(text => {
                            console.log('Error response text:', text);
                            throw new Error(text || '获取教师信息失败');
                        });
                    }
                    return response.json();
                })
                .then(teacher => {
                    console.log('Teacher data received:', teacher);
                    
                    // 恢复表单内容
                    document.getElementById('editTeacherForm').innerHTML = `
                        <input type="hidden" id="editTeacherId" name="teacherId">
                        <input type="hidden" id="editUserId" name="userId">
                        <div class="form-group">
                            <label for="editName">姓名</label>
                            <input type="text" id="editName" name="name" required>
                        </div>
                        <div class="form-group">
                            <label for="editGender">性别</label>
                            <select id="editGender" name="gender" required>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editDepartment">院系</label>
                            <input type="text" id="editDepartment" name="department" required>
                        </div>
                        <div class="form-group">
                            <label for="editTitle">职称</label>
                            <select id="editTitle" name="title" required>
                                <option value="教授">教授</option>
                                <option value="副教授">副教授</option>
                                <option value="助教">助教</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editBirthDate">出生日期</label>
                            <input type="date" id="editBirthDate" name="birthDate" required>
                        </div>
                        <div class="form-group">
                            <label for="editHireDate">入职日期</label>
                            <input type="date" id="editHireDate" name="hireDate" required>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                            <button type="button" class="btn-submit" onclick="updateTeacher()">保存</button>
                        </div>
                    `;
                    
                    // 填充表单数据
                    document.getElementById('editTeacherId').value = teacher.teacherId;
                    document.getElementById('editUserId').value = teacher.userId;
                    document.getElementById('editName').value = teacher.name;
                    document.getElementById('editGender').value = teacher.gender;
                    document.getElementById('editDepartment').value = teacher.department;
                    document.getElementById('editTitle').value = teacher.title;
                    document.getElementById('editBirthDate').value = formatDate(teacher.birthDate);
                    document.getElementById('editHireDate').value = formatDate(teacher.hireDate);
                })
                .catch(error => {
                    console.error('获取教师信息失败:', error);
                    document.getElementById('editTeacherForm').innerHTML = `
                        <div style="text-align: center; color: red; padding: 20px;">
                            加载失败: ${error.message}
                            <div class="form-actions" style="margin-top: 20px;">
                                <button type="button" class="btn-cancel" onclick="closeEditModal()">关闭</button>
                            </div>
                        </div>
                    `;
                });
        }

        // 关闭编辑教师模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新教师
        function updateTeacher() {
            const teacherId = document.getElementById('editTeacherId').value;
            const userId = document.getElementById('editUserId').value;
            const name = document.getElementById('editName').value.trim();
            const gender = document.getElementById('editGender').value;
            const department = document.getElementById('editDepartment').value.trim();
            const title = document.getElementById('editTitle').value;
            const birthDate = document.getElementById('editBirthDate').value;
            const hireDate = document.getElementById('editHireDate').value;

            console.log('Updating teacher with ID:', teacherId);

            if (!name || !department || !birthDate || !hireDate) {
                alert('请填写所有必填字段');
                return;
            }

            // 禁用保存按钮，防止重复提交
            const saveButton = document.querySelector('#editModal .btn-submit');
            const cancelButton = document.querySelector('#editModal .btn-cancel');
            
            if (saveButton) {
                saveButton.disabled = true;
                saveButton.textContent = '保存中...';
            }
            if (cancelButton) {
                cancelButton.disabled = true;
            }

            const teacher = {
                teacherId,
                userId: parseInt(userId),
                name,
                gender,
                department,
                title,
                birthDate,
                hireDate
            };

            console.log('Updating teacher with data:', teacher);

            fetch(`/api/admin/teachers/${encodeURIComponent(teacherId)}`, {
                method: 'PUT',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(teacher)
            })
                .then(response => {
                    console.log('Update response status:', response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('教师不存在');
                            throw new Error('教师不存在');
                        }
                        return response.text().then(text => {
                            console.log('Error updating teacher:', text);
                            throw new Error(text || '更新教师失败');
                        });
                    }
                    return response.json();
                })
                .then((responseData) => {
                    console.log('Teacher updated successfully:', responseData);
                    closeEditModal();
                    fetchTeachers();
                    alert('教师信息更新成功！');
                })
                .catch(error => {
                    console.error('更新教师失败:', error);
                    alert('更新教师失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (saveButton) {
                        saveButton.disabled = false;
                        saveButton.textContent = '保存';
                    }
                    if (cancelButton) {
                        cancelButton.disabled = false;
                    }
                });
        }

        // 删除教师
        function deleteTeacher(teacherId) {
            console.log("准备删除教师，ID:", teacherId);
            if (!confirm('确定要删除此教师吗？此操作不可恢复，将同时删除关联的用户信息。')) {
                return;
            }

            fetch(`/api/admin/teachers/${encodeURIComponent(teacherId)}`, {
                method: 'DELETE',
                credentials: 'include'
            })
                .then(response => {
                    console.log("删除教师响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('教师不存在');
                            throw new Error('教师不存在');
                        } else if (response.status === 409) {
                            alert('该教师已有关联课程，无法删除');
                            throw new Error('该教师已有关联课程');
                        }
                        return response.text().then(text => { throw new Error(text || '删除教师失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    console.log("删除教师成功");
                    alert('删除教师成功');
                    fetchTeachers();
                })
                .catch(error => {
                    console.error('删除教师出错:', error);
                    alert('删除教师失败: ' + error.message);
                });
        }
    </script>
</body>

</html>